﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace SFast
{
    public static class EnumsExtensions
    {
        /// <summary>
        /// 获取枚举的Remark特性中的Remark的值
        /// </summary>
        /// <param name="_enum">枚举</param>
        /// <returns></returns>
        public static string _GetRemark(this System.Enum _enum)
        {
            Type type = _enum.GetType();
            FieldInfo fd = type.GetField(_enum.ToString());
            if (fd == null) return string.Empty;
            object[] attrs = fd.GetCustomAttributes(typeof(SFast.Enums.RemarkAttribute), false);
            string name = string.Empty;
            foreach (SFast.Enums.RemarkAttribute attr in attrs)
            {
                name = attr.Remark;
            }
            return name;
        }


        /// <summary>
        /// 获取枚举中的指定特性（继承Attribute的类）
        /// </summary>
        /// <typeparam name="T">特性类（继承Attribute的类）</typeparam>
        /// <param name="_enum">枚举</param>
        /// <returns>继承Attribute的类对象</returns>
        public static T _GetRemark<T>(this System.Enum _enum)
        {
            Type type = _enum.GetType();
            FieldInfo fd = type.GetField(_enum.ToString());
            if (fd == null) return default(T);
            object[] attrs = fd.GetCustomAttributes(typeof(T), false);
            if (attrs.Length>0)
            {
                return (T)attrs.First();
            }
            else
            {
                return default(T);
            }
        }

        /// <summary>
        /// 通过备注值转换成枚举类型
        /// </summary>
        /// <param name="str">枚举备注</param>
        /// <returns></returns>
        public static T _RemarkToEnum<T>(this String str)
        {
            Type type = typeof(T);
            FieldInfo[] fis = type.GetFields();
            FieldInfo fi = fis.Where(o => 
                {
                    var attrs = o.GetCustomAttributes(typeof(SFast.Enums.RemarkAttribute), false);
                    if (attrs.Length>0)
	                {
		                return (attrs[0] as SFast.Enums.RemarkAttribute).Remark == str;
	                }
                    return false;
                }
                ).FirstOrDefault();
            if (fi == null)
            {
                return default(T);
            }
            return (T)Enum.Parse(typeof(T), fi.Name);
        }
    }
}
